<?php

namespace Mlym\CodeGeneration\Middleware;


use EasySwoole\ORM\Utility\Schema\Table;
use Mlym\CodeGeneration\Middleware\Api\Api;
use Mlym\CodeGeneration\Middleware\Api\Config;
use Mlym\CodeGeneration\Middleware\Api\Validate;
use Mlym\CodeGeneration\Middleware\Bean\MiddlewareBean;

/**
 * 中间件数据生成
 * Class MiddlewareGeneration
 * @author Ryan <43352901@qq.com>
 * @date 6/14/21 1:01 PM
 * @package Mlym\CodeGeneration\Middleware
 */
class MiddlewareGeneration
{
    protected $config;
    protected $data;
    protected $table;

    public function __construct($moduleName)
    {
        $this->config = new Config(\EasySwoole\EasySwoole\Config::getInstance()->getConf('WISE_GENERATOR'));
        $this->config->setModule($moduleName);
    }

    /**
     * 获取中间件数据对象
     * @throws \Exception
     */
    public function getMiddlewareData(): MiddlewareBean
    {
        if (empty($this->data)) {
            $api = new Api($this->config);
            $this->data = new MiddlewareBean($api->request() ?? []);
            $validate = new Validate($this->data);
            if (!$validate->validate()) {
                throw new \Exception($validate->getMessage());
            }
        }
        return $this->data;
    }

    /**
     * 获取Table表对象
     * @throws \Exception
     */
    public function getTable(): Table
    {
        if (empty($this->table)) {
            $tableGeneration = new TableGeneration($this->getMiddlewareData()->getModule());
            $this->table = $tableGeneration->generate();
        }
        return $this->table;
    }


}